<?php

namespace app\controller;

use app\BaseController;
use app\controller\admin\Order;
use app\Log;
use app\model\Account;
use app\model\CouponOrder;
use app\model\ProductAttr;
use app\model\Supplier;
use app\model\User;
use app\model\UserBalance;
use cgas\CGas;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use fuhai\Fuhai;
use think\facade\Cache;
use think\response\Json;

class FuhaiApi extends BaseController
{
    public function product(): Json
    {
        try {
            $author = $this->request->header("authorization");
            if (empty($author)) throw new \Exception("请先登录", 7001);
            $author = json_decode($author, true);
            $account = $this->app->make(Account::class)->where(['id' => $author['id']])->find();
            if (empty($account['supplier_id'])) throw new \Exception("请先绑定供应商", 7001);
            $supplier = $this->app->make(Supplier::class)->where(['id' => $account['supplier_id']])->find();
            if (empty($supplier)) throw new \Exception("请先绑定供应商", 7001);
            $data = $this->app->make(Fuhai::class, ['appid' => $supplier['fuhai_appid'], 'appsecret' => $supplier['fuhai_appsecret']])->setApi("product/lst")->setData([
                "page" => 1,
                "size" => 1000
            ])->send();
            if (empty($data) || $data['code'] != 0) return $this->success([]);
            return $this->success($data['data']['data']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function package()
    {
        try {
            $author = $this->request->header("authorization");
            if (empty($author)) throw new \Exception("请先登录", 7001);
            $author = json_decode($author, true);
            $account = $this->app->make(Account::class)->where(['id' => $author['id']])->find();
            if (empty($account['supplier_id'])) throw new \Exception("请先绑定供应商", 7001);
            $supplier = $this->app->make(Supplier::class)->where(['id' => $account['supplier_id']])->find();
            if (empty($supplier)) throw new \Exception("请先绑定供应商", 7001);
            $data = $this->app->make(Fuhai::class, ['appid' => $supplier['fuhai_appid'], 'appsecret' => $supplier['fuhai_appsecret']])->setApi("package/lst")->setData([
                "page" => 1,
                "size" => 1000
            ])->send();
            if (empty($data) || $data['code'] != 0) return $this->success([]);
            return $this->success($data['data']['data']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function create(): Json
    {
        $param = $this->request->param();
        $model = $this->app->make(\app\model\Order::class);
        $cache = Cache::get("cgas-$param[mobile]-$param[order]");
        if (!empty($cache)) {
            $this->app->make(Log::class, ['dir' => 'third_api'])->write(['params' => $param]);
            return json(['errorCode' => 1, 'errorMessage' => '重复提交订单！']);
        }
        Cache::set("cgas-$param[mobile]-$param[order]", 1, 60);
        //获取产品
        $code = $param['code'] ?? "";
        //获取产品信息
        $product = $this->app->make(ProductAttr::class)->where(['code' => 'cgas-' . $code])->find();
        if (empty($product) || $product['stock'] < 1) return json(['errorCode' => 1, 'errorMessage' => '产品不存在！']);
        //创建订单
        $user = $this->app->make(User::class)->where(['mobile' => '13281112344'])->find();
        if (empty($user)) return json(['errorCode' => 1, 'errorMessage' => '用户不存在！']);
        $user->startTrans();
        $count = $model->where(['order_sn' => $param['order'], 'uid' => $user['id']])->find();
        if (!empty($count)) {
            return \json([
                "errorCode" => 0,
                "result" => json_decode($count['cont'], true)
            ]);
        }
        //获取是否存在订单
        $model->exists(false)->save([
            "order_sn" => $param['order'],
            "product_id" => $product['pid'],
            "attr_id" => $product['id'],
            "uid" => $user['id'],
            "price" => bcmul($product['price'], 100),
            "account" => json_encode([
                [
                    'name' => '手机号',
                    'text' => 'mobile',
                    'value' => $param['mobile'],
                    'required' => true,
                    'rules' => '/^1[2-9]\d{9}$/'
                ]
            ], 320),
            "is_del" => 1,
            "state" => 1
        ]);
        //扣减积分
        $user->dec('balance', bcmul($product['price'], 100))->save();
        //生成扣减日志
        app(UserBalance::class)->save([
            "uid" => $user['id'],
            "number" => bcmul($product['price'], 100),
            "type" => 2,
            "content" => "富海车生活兑换中石油加油券",
        ]);
        $cga = app(CGas::class)->pay($code, $param['mobile'], $param['order']);
        if ($cga['code'] == 0) {
            $cga = $cga['data']['ticket_list'];
            $model->save(["code" => $cga[0]['ticket_num'],
                "cont" => json_encode($cga, 320)]);
            //扣减产品库存
            $product->dec("stock", 1)->save();
            $user->commit();
            return json([
                "errorCode" => 0,
                "result" => $cga
            ]);
        }
        //扣减产品库存
        $product->dec("stock", 1)->save();
        $user->commit();
        return json([
            "errorCode" => 1,
            "errorMessage" => "接口请求异常"
        ]);

    }

    public function stationOrder(): Json
    {
        $param = $this->request->param();
        $model = $this->app->make(\app\model\Order::class);
        $cache = Cache::get("csgas-$param[mobile]-$param[order]");
        if (!empty($cache)) {
            $this->app->make(Log::class, ['dir' => 'third_api_gas'])->write(['params' => $param]);
            return json(['errorCode' => 1, 'errorMessage' => '重复提交订单！']);
        }
        Cache::set("csgas-$param[mobile]-$param[order]", 1, 60);
        //获取产品
        $code = $param['code'] ?? "";
        //获取产品信息
        $product = $this->app->make(ProductAttr::class)->where(['code' => 'cgas-' . $code])->find();
        if (empty($product) || $product['stock'] < 1) return json(['errorCode' => 1, 'errorMessage' => '产品不存在！']);
        //创建订单
        $user = $this->app->make(User::class)->where(['mobile' => '13281112344'])->find();
        if (empty($user)) return json(['errorCode' => 1, 'errorMessage' => '用户不存在！']);
        $user->startTrans();
        $count = $model->where(['order_sn' => $param['order'], 'uid' => $user['id']])->find();
        if (!empty($count)) {
            return \json([
                "errorCode" => 0,
                "result" => json_decode($count['cont'], true)
            ]);
        }
        //获取是否存在订单
        $model->exists(false)->save([
            "order_sn" => $param['order'],
            "product_id" => $product['pid'],
            "attr_id" => $product['id'],
            "uid" => $user['id'],
            "price" => bcmul($product['price'], 100),
            "account" => json_encode([
                [
                    'name' => '手机号',
                    'text' => 'mobile',
                    'value' => $param['mobile'],
                    'required' => true,
                    'rules' => '/^1[2-9]\d{9}$/'
                ]
            ], 320),
            "is_del" => 1,
            "state" => 1
        ]);
        //扣减积分
        $user->dec('balance', bcmul($product['price'], 100))->save();
        //生成扣减日志
        app(UserBalance::class)->save([
            "uid" => $user['id'],
            "number" => bcmul($product['price'], 100),
            "type" => 2,
            "content" => "中油拉新兑换",
        ]);
        $cga = app(CGas::class)->pay($code, $param['mobile'], $param['order']);
        if ($cga['code'] == 0) {
            $cga = $cga['data']['ticket_list'];
            $model->save(["code" => $cga[0]['ticket_num'],
                "cont" => json_encode($cga, 320)]);
            //扣减产品库存
            $product->dec("stock", 1)->save();
            $user->commit();
            return json([
                "errorCode" => 0,
                "result" => $cga
            ]);
        }
        //扣减产品库存
        $product->dec("stock", 1)->save();
        $user->commit();
        return json([
            "errorCode" => 1,
            "errorMessage" => "接口请求异常"
        ]);
    }

    public function stationOrderRefund(): Json
    {
        $param = $this->request->param();
        $model = $this->app->make(\app\model\Order::class);
        if (Cache::has("station_order_refund_" . $param["order_id"])) {
            $this->app->make(Log::class, ['dir' => 'third_api_gas_refund'])->write(['params' => $param]);
            return json([
                "errorCode" => 1,
                "errorMessage" => "请勿重复提交"
            ]);
        }
        Cache::set("station_order_refund_" . $param["order_id"], 1, 60);
        $order = $model->where("order_sn", $param["order_id"])->where('state', 1)->find();
        if (empty($order)) {
            $this->app->make(Log::class, ['dir' => 'third_api_gas_refund'])->write(['params' => $param]);
            return json([
                "errorCode" => 1,
                "errorMessage" => "订单不存在"
            ]);
        }
        $product = $this->app->make(ProductAttr::class);
        if (env("line.run")) {
            // 向中石油退单
            if (!empty($order['code'])) {
                $query = $this->app->make(CGas::class)->cancel($order['code']);
                if ($query['code'] != 0) {
                    return json([
                        "errorCode" => 1,
                        "errorMessage" => "中油券退单失败"
                    ]);
                }
//            } else {
//                @file_get_contents("https://pandalife.store/index/queryCode");
//                sleep(1);
//                return json([
//                    "errorCode" => 1,
//                    "errorMessage" => "订单异常，请稍后重试"
//                ]);
            }
        }
        $model->startTrans();
        // 订单退单
        $order->save(['state' => 5, "cancel_time" => date("Y-m-d H:i:s")]);
        // 回退产品库存
        $product->where(['id' => $order->attr_id])->inc("stock", 1)->save();
        // 退回用户积分
        $this->app->make(User::class)->where(['id' => $order->uid])->inc("balance", $order->price)->save();
        //记录过期积分
        // 记录退回日志
        app(UserBalance::class)->save([
            "uid" => $order['uid'],
            "number" => $order->price,
            "type" => 1,
            "content" => "系统退单",
        ]);
        $model->commit();
        return json([
            "errorCode" => 0,
            "errorMessage" => "退单成功"
        ]);
    }

    public function autoClearCoupon(): Json
    {
        $model = $this->app->make(CouponOrder::class);
        $order = $model->with(['thirdCoupon' => function ($query) {
            $query->with(['coupon']);
        }])->where(['state' => 1])->select()->toArray();
        $update = [];
        if (!empty($order)) {
            foreach ($order as $v) {
                $third = $v['thirdCoupon'] ?? [];
                unset($v['thirdCoupon'], $v['update_time']);
                if (!empty($third)) {
                    if (empty($third['coupon'])) {
                        $v['state'] = 2;
                        $update[] = $v;
                    } else {
                        $coupon = $third['coupon'];
                        if (time() > $coupon['term']) {
                            $v['state'] = 3;
                            $update[] = $v;
                        } else if ($coupon['state'] > 0) {
                            $v['state'] = match ($v['state']) {
                                1 => 5,
                                default => 3,
                            };
                            $update[] = $v;
                        }
                    }
                } else {
                    $v['state'] = 2;
                    $update[] = $v;
                }
            }
        }

        if (!empty($update)) {
            $model->exists()->saveAll($update);
        }
        return json(['code' => 0, 'message' => '成功', 'date' => $update]);
    }

    public function queryBalance(): Json
    {
        $log = new Log('third_api_gas_query_balance');
        //创建订单
        $user = $this->app->make(User::class)->where(['mobile' => '13281112344'])->find();
        if (empty($user)) return \json(['code' => 1, 'message' => '用户不存在']);
        //判断
        $money = $this->request->param('money');
        $balance = bcsub($user['balance'], bcmul($money, 100), 2);
        $max = config('fuhai.max_money');
        $log->write(['params' => $this->request->param(), 'balance' => abs($balance), 'max' => abs($max), 'user' => $user->toArray()]);
        if (abs($balance) >= abs($max)) return json(['code' => 1, 'message' => '最高透支金额' . bcdiv($max, 100)]);
        return json(['code' => 0, 'message' => '成功', 'balance' => $balance]);
    }

    public function queryCoupon(): Json
    {
        $code = $this->request->param('code');
        $order = $this->app->make(\app\model\Order::class)->where('order_sn', $code)->find();
        if (empty($order)) return json(['code' => 1, 'message' => '订单不存在']);
        return json(['code' => 0, 'message' => '成功', 'coupon' => $order]);
    }
}
